package com.zhao.dota.processor;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.net.URLEncoder;

@Component
@Slf4j
public class QiniuProcessor {

    private static final String REPLY_BUCKET_NAME = "reply";

    private static final String cdn = "http://cdn.dota.link/";

    @Resource
    private OkHttpClient downOkHttpClient;

    @Value("${qiniu.access-key:}")
    private String accessKey;
    @Value("${qiniu.secret-key:}")
    private String secretKey;

    public boolean uploadReply(File file, String name) {
        Configuration cfg = new Configuration(Region.huabei());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String localFilePath = file.getPath();
        //默认不指定key的情况下，以文件内容的hash值作为文件名

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(REPLY_BUCKET_NAME);
        try {
            Response response = uploadManager.put(localFilePath, name, upToken);
            return response.isOK();
            //解析上传成功的结果
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error("七牛云上传失败, toString: {}", r.toString());
            try {
                log.error("七牛云上传失败, body: {}", r.bodyString());
            } catch (QiniuException ignored) {
            }
        }
        return false;
    }

    @SneakyThrows
    public byte[] downloadReply(String name) {
        String fileName = cdn + URLEncoder.encode(name, "utf-8").replace("+", "%20");
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 3600;
        String finalUrl = auth.privateDownloadUrl(fileName, expireInSeconds);
        Request get = new Request.Builder()
                .get()
                .url(finalUrl).build();
        Call call = downOkHttpClient.newCall(get);
        okhttp3.Response response = call.execute();
        byte[] bytes = response.body().bytes();
        return bytes;
    }

    public boolean replyExists(String name) {
        Configuration cfg = new Configuration(Region.huabei());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            FileInfo stat = bucketManager.stat(REPLY_BUCKET_NAME, name);
            return true;
        } catch (QiniuException e) {
            return false;
        }
    }

    public String uploadToken(String filename) {
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(REPLY_BUCKET_NAME, filename);
    }

}
